import React, { useEffect, useState } from 'react';
import ProForm, { ProFormList, ProFormText } from '@dtfe/pro-form';
import { Form } from 'antd';

// 提交的时候转换数据
const transValue = (value) => {
  if (value) {
    const valueList = value
      .filter((item) => !item || (item && Object.keys(item).length > 0))
      .map((item) => `${item?.ip ? item?.ip : undefined}:${item?.host ? item?.host : undefined}`); // 修复删除某个字段改行清空问题
    return valueList.join(',');
  }
};

// 回显的时候转换数据
const transInitValue = (value = '') => {
  if (!value) return;
  return value.split(',').map((item) => {
    const aItem = item.split(':');
    return {
      ip: aItem[0],
      host: aItem[1],
    };
  });
};
const Proformlist = ({ value = '', initialValue = '', onChange, disabled = false }) => {
  // const [form] = ProForm.useForm(); // eslint-disable-line
  const [form] = Form.useForm();
  // 修改删除不掉和输入失效的问题
  const [operatedVisible, setOperatedVisible] = useState(false); // 标记用户首次操作，操作之后initialValue不再生效
  useEffect(() => {
    if (!operatedVisible) {
      form.setFieldsValue({
        proFormList: transInitValue(initialValue),
      });
    }
  }, [initialValue]);
  return (
    <div>
      <ProForm
        form={form}
        submitter={false}
        onValuesChange={(_, values) => {
          if (!operatedVisible) setOperatedVisible(true);
          onChange?.(transValue(values.proFormList));
        }}
        style={{ minWidth: '600px' }}
      >
        <ProFormList
          name="proFormList"
          creatorButtonProps={
            !disabled && {
              position: 'bottom',
              disabled,
            }
          }
          copyIconProps={!disabled}
          deleteIconProps={!disabled}
          initialValue={transInitValue(value)}
          style={{ margin: '0px', padding: '0px' }}
        >
          <ProForm.Group size={8}>
            <ProFormText
              name="ip"
              placeholder="请输入"
              rules={[
                { required: true, message: '请输入ip' },
                {
                  pattern: /^[\x20-\x2B\x2D-\x39\x3B-\x3F\x41-\x7E]*$/,
                  message:
                    '请输入由英文、数字以及除“:”、“,”、“@”之外的英文特殊字符组成，1~128个字符。',
                },
              ]}
              disabled={disabled}
            />
            <ProFormText
              name="host"
              placeholder="请输入"
              rules={[
                { required: true, message: '请输入host' },
                {
                  pattern: /(^\s{0,})([1-9]\d{0,3}|[1-5]\d\d\d\d|6[0-4]\d\d\d|65[0-4]\d\d|655[0-2]\d|6553[0-5])(\s{0,}$)/,
                  message: '请输入1~65535的整数',
                },
              ]}
              disabled={disabled}
            />
          </ProForm.Group>
        </ProFormList>
      </ProForm>
    </div>
  );
};
export default Proformlist;
